export default {
	namespaced: true,
	state: () => ({
		cart: JSON.parse(uni.getStorageSync('cart') || '[]')
	}),
	mutations: {
		// 支付
		updateCart(state,cart){
			state.cart=cart
			// 持久化存储
			this.commit('m_cart/saveTostorage')
		},
		// 全选反选
		updateAllChecked(state,checked){
			state.cart.forEach(e=>e.goods_state=checked)
			// 持久化存储
			this.commit('m_cart/saveTostorage')
		},
		// 删除商品
		updateRemoveGoods(state, goods){
			state.cart = state.cart.filter(e=>e.goods_id!==goods.goods_id)
			// 持久化存储
			this.commit('m_cart/saveTostorage')
		},
		// 修改商品数量
		updateGoodscount(state, goods){
			// 找到商品
			const findRes = state.cart.find(e => e.goods_id === goods.goods_id)
			if(!!findRes){
				// 修改goods_count
				findRes.goods_count = goods.goods_count
			}
			// 持久化存储
			this.commit('m_cart/saveTostorage')
		},
		// 更改选中状态
		updateGoodsState(state, goods) {
			// 在数组中找到要修改到对象
			const findRes = state.cart.find(e => e.goods_id === goods.goods_id)
			if (!!findRes) {
				// 吧他的goods——state取返
				findRes.goods_state = !findRes.goods_state
			}
			// 持久化存储
			this.commit('m_cart/saveTostorage')
		},
		// 加入购物车
		updateAddCart(state, goods) {
			// 找到是否存在这件商品
			const findRes = state.cart.find(e => e.goods_id === goods.goods_id)
			if (!!findRes) {
				// 如果存在就上数量加一
				findRes.goods_count++
			} else {
				// 如果不存在就push
				state.cart.push(goods)
			}
			console.log(state.cart)
			// 持久化存储
			this.commit('m_cart/saveTostorage')
		},
		saveTostorage(state) {
			uni.setStorageSync('cart', JSON.stringify(state.cart))
		}
	},
	getters: {
		// 以勾选商品总金额
		checkedPrice(state){
			let sum = 0
			state.cart.forEach(e=>{
				if(e.goods_state){
					sum += (e.goods_price * e.goods_count)
				}
				
			})
			return sum.toFixed(2)
		},
		// 商品勾选到数量
		checkedCount(state){
			let sum = 0
			state.cart.forEach(e=>{
				if(e.goods_state){
					sum += e.goods_count
				}
				
			})
			return sum 
		},
		// 全部商品的数据
		allGoodsCount(state) {
			let sum = 0
			state.cart.forEach(e => {
				sum += e.goods_count
			})
			return sum
		}
	}
}
